How to sort with lambda in Python Programming?
How to sort with lambda in Python Programming?
23217-Aug-2023
Updated on 18-Aug-2023
Home / DeveloperSection / Forums / How to sort with lambda in Python Programming?
How to sort with lambda in Python Programming?
Aryan Kumar
18-Aug-2023Sure, I can help you with that.
To sort with lambda in Python programming, you can use the
sorted()
function. Thesorted()
function takes a list as its argument and returns a new list that is sorted according to the specified criteria. The criteria can be specified using a lambda expression.The syntax for the
sorted()
function is as follows:Python
list
: The list to be sorted.key
: A lambda expression that specifies the criteria for sorting. The lambda expression takes an element from the list as its input and returns a value that will be used to sort the element.The following code sorts a list of names in ascending order by their first letter:
Python
In this code, the
sorted()
function takes thenames
list as its argument and returns a new list that is sorted by the first letter of each name. The lambda expression takes a name as its input and returns the first letter of the name.The
sorted()
function can also be used to sort a list of numbers. The following code sorts a list of numbers in ascending order:Python
In this code, the
sorted()
function takes thenumbers
list as its argument and returns a new list that is sorted by the numbers. The lambda expression takes a number as its input and returns the number itself.